package com.atguigu.tingshu.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
//import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.db.sql.Order;
import com.atguigu.tingshu.account.AccountFeignClient;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.delay.DelayMssage;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.order.OrderDerate;
import com.atguigu.tingshu.model.order.OrderDetail;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.order.helper.SignHelper;
import com.atguigu.tingshu.order.mapper.OrderDerateMapper;
import com.atguigu.tingshu.order.mapper.OrderDetailMapper;
import com.atguigu.tingshu.order.mapper.OrderInfoMapper;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.atguigu.tingshu.user.client.UserFeignClient;
import com.atguigu.tingshu.vo.account.AccountLockVo;
import com.atguigu.tingshu.vo.order.OrderDerateVo;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AlbumFeignClient albumFeignClient;
    @Autowired
    private OrderDetailMapper detailMapper;
    @Autowired
    private OrderDerateMapper derateMapper;
    @Autowired
    private AccountFeignClient accountFeignClient;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private DelayMssage delayMessage;


    @Override
    public OrderInfoVo tradeOrderData(Long userId, TradeVo tradeVo) {
        //创建订单
        /**该方法是重用代码 可支持专辑、声音、会员订单的生成
         *根据itemID去对应类型的数据中查找数据
         *
         */
        //初始化订单数据
        OrderInfoVo orderInfoVo = new OrderInfoVo();
        BigDecimal originAmount = new BigDecimal("0.00");
        BigDecimal decrateAmount = new BigDecimal("0.00");
        BigDecimal orderAmount = new BigDecimal("0.00");
        List<OrderDetailVo> orderDetailVoList = new ArrayList<>();
        List<OrderDerateVo> orderDerateVoList = new ArrayList<>();

        String itemType = tradeVo.getItemType();
        //会员订单的数据处理
        if (SystemConstant.ORDER_ITEM_TYPE_VIP.equals(itemType)) {
            Result<VipServiceConfig> vipServiceConfigR = userFeignClient.getVipServiceConfig(tradeVo.getItemId());
            Assert.notNull(vipServiceConfigR, "获取vip套餐信息失败！" + tradeVo.getItemId());
            VipServiceConfig vipServiceConfig = vipServiceConfigR.getData();
            originAmount = vipServiceConfig.getPrice();
            decrateAmount = vipServiceConfig.getDiscountPrice();
            orderAmount = originAmount.subtract(decrateAmount);
            //封装OrderDetailVo
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            orderDetailVo.setItemUrl(vipServiceConfig.getImageUrl());
            orderDetailVo.setItemId(tradeVo.getItemId());
            orderDetailVo.setItemPrice(vipServiceConfig.getPrice());
            orderDetailVo.setItemName(vipServiceConfig.getName());
            orderDetailVoList.add(orderDetailVo);
            //封装OrderDerateVo
            OrderDerateVo orderDerateVo = new OrderDerateVo();
            orderDerateVo.setDerateAmount(vipServiceConfig.getDiscountPrice());
            orderDerateVo.setRemarks("VIP限时优惠：" + decrateAmount);
            orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_VIP_SERVICE_DISCOUNT);
            orderDerateVoList.add(orderDerateVo);
        } else if (SystemConstant.ORDER_ITEM_TYPE_ALBUM.equals(tradeVo.getItemType())) {
            //专辑订单的生成
            //根据传递进来的专辑D 判断该专辑·是否已被用户购买
            //根据专辑ID中的声音总数*声音价格计算出专辑的originAmount 根据减免条件计算DecrateAmount 根据以上价格计算orderAmount
            Boolean isPaidAlbum = userFeignClient.isPaidAlbum(tradeVo.getItemId()).getData();

            Assert.notNull(isPaidAlbum, "查询用户支付专辑数据失败");
            if (isPaidAlbum) {
                throw new GuiguException(400, "当前用户已购买该专辑！");
            }
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            AlbumInfo albumInfo = albumFeignClient.getAlbumInfo(tradeVo.getItemId()).getData();
            Assert.notNull(albumInfo, "获取" + albumInfo.getId() + "专辑数据失败");

            originAmount = albumInfo.getPrice().multiply(new BigDecimal(albumInfo.getIncludeTrackCount()));
            orderAmount = originAmount;
            UserInfoVo userInfoVo = userFeignClient.getUserVoById(userId).getData();
            Assert.notNull(userInfoVo, "用户信息未查询成功");
            Integer isVip = userInfoVo.getIsVip();
            //3.4.1 判断专辑是否有普通用户折扣
            BigDecimal discount = albumInfo.getDiscount();
            if (discount.intValue() != -1) {
                if (isVip.intValue() == 0 || (isVip.intValue() == 1 && new Date().after(userInfoVo.getVipExpireTime()))) {
                    //普通用户折扣(从0.1-9.9)：原价*折扣   100*8/10 = 80 注意：保留小数位+四舍五入
                    orderAmount = originAmount.multiply(discount)
                            .divide(new BigDecimal("10"), 2, RoundingMode.HALF_UP);
                }
            }
            //3.4.2 判断专辑是否有VIP用户折扣
            BigDecimal vipDiscount = albumInfo.getVipDiscount();
            if (vipDiscount.intValue() != -1) {
                if (isVip.intValue() == 1) {
                    //VIP会员用户
                    orderAmount = originAmount.multiply(vipDiscount)
                            .divide(new BigDecimal("10"), 2, RoundingMode.HALF_UP);
                }
            }
            decrateAmount = originAmount.subtract(orderAmount).setScale(2, RoundingMode.HALF_UP);
            //3.5 封装订单中商品明细列表（专辑）
            orderDetailVo.setItemId(tradeVo.getItemId());
            orderDetailVo.setItemName(albumInfo.getAlbumTitle());
            orderDetailVo.setItemUrl(albumInfo.getCoverUrl());
            orderDetailVo.setItemPrice(originAmount);
            orderDetailVoList.add(orderDetailVo);
            //3.6 封装订单中优惠明细列表
            if (decrateAmount.doubleValue() > 0) {
                OrderDerateVo orderDerateVo = new OrderDerateVo();
                orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_ALBUM_DISCOUNT);
                orderDerateVo.setDerateAmount(decrateAmount);
                orderDerateVo.setRemarks("专辑优惠：" + decrateAmount);
                orderDerateVoList.add(orderDerateVo);
            }
        } else if (SystemConstant.ORDER_ITEM_TYPE_TRACK.equals(itemType)) {
            Long trackId = tradeVo.getItemId();
            Integer trackCount = tradeVo.getTrackCount();
            TrackInfo trackInfo = albumFeignClient.getTrackInfo(trackId).getData();
            if (trackInfo == null) {
                throw new GuiguException(500, "获取声音信息失败,id:" + trackId);
            }
            Long albumId = trackInfo.getAlbumId();
            AlbumInfo albumInfo = albumFeignClient.getAlbumInfo(albumId).getData();
            if (albumInfo == null) {
                throw new GuiguException(500, "获取专辑信息失败,id:" + albumId);
            }
            BigDecimal discount = albumInfo.getDiscount();
            BigDecimal vipDiscount = albumInfo.getVipDiscount();
            BigDecimal price = albumInfo.getPrice();

            //获取到已过滤的声音IDlist 根据声音ID去查找顺序后的声音及用户已购买声音过滤的结果
            List<TrackInfo> checkTrackList = albumFeignClient.findPaidTrackInfoList(trackId, tradeVo.getTrackCount()).getData();
            if (CollectionUtil.isEmpty(checkTrackList)) {
                throw new GuiguException(500, "该声音购买有异常");
            }
            for (TrackInfo info : checkTrackList) {
                OrderDetailVo orderDetailVo = new OrderDetailVo();
                orderDetailVo.setItemUrl(info.getCoverUrl());
                orderDetailVo.setItemId(info.getId());
                orderDetailVo.setItemName(info.getTrackTitle());
                orderDetailVo.setItemPrice(price);
                orderDetailVoList.add(orderDetailVo);
            }
            int count = checkTrackList.size();
            BigDecimal sum = new BigDecimal("0.00");
            originAmount = price.multiply(new BigDecimal(count));
            UserInfoVo userInfoVo = userFeignClient.getUserVoById(userId).getData();
            if (discount.intValue() != -1) {
                System.out.println(1 == userInfoVo.getIsVip() && new Date().after(userInfoVo.getVipExpireTime()));
                System.out.println(new Date().after(userInfoVo.getVipExpireTime()));
                if ((1 == userInfoVo.getIsVip() && new Date().after(userInfoVo.getVipExpireTime())) || 0 == userInfoVo.getIsVip()) {
                    sum = originAmount.multiply(discount);
                    decrateAmount = originAmount.subtract(sum).setScale(2, RoundingMode.HALF_UP);
                    OrderDerateVo orderDerateVo = new OrderDerateVo();
                    orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_ALBUM_DISCOUNT);
                    orderDerateVo.setDerateAmount(decrateAmount);
                    orderDerateVo.setRemarks("专辑：" + albumInfo.getAlbumTitle() + "折扣：" + discount);
                    orderDerateVoList.add(orderDerateVo);
                }
            } else if (vipDiscount.intValue() != -1) {
                if (1 == userInfoVo.getIsVip() && new Date().before(userInfoVo.getVipExpireTime())) {
                    sum = originAmount.multiply(vipDiscount);
                    decrateAmount = originAmount.subtract(sum).setScale(2, RoundingMode.HALF_UP);
                    OrderDerateVo orderDerateVo = new OrderDerateVo();
                    orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_VIP_SERVICE_DISCOUNT);
                    orderDerateVo.setDerateAmount(decrateAmount);
                    orderDerateVo.setRemarks("专辑：" + albumInfo.getAlbumTitle() + "折扣：" + vipDiscount);
                    orderDerateVoList.add(orderDerateVo);
                }
            }
            orderAmount = originAmount.subtract(decrateAmount).setScale(2, RoundingMode.HALF_UP);
        }
//        5.1.1 构建当前用户本次订单流水号Key
        String tradeNoKey = RedisConstant.ORDER_TRADE_NO_PREFIX + userId;
        //5.1.2 生成本次订单流水号
        String tradeNo = IdUtil.fastSimpleUUID();
        redisTemplate.opsForValue().set(tradeNoKey, tradeNo, 5, TimeUnit.MINUTES);
        //封装ORderInfoVo
        orderInfoVo.setOrderAmount(orderAmount);
        orderInfoVo.setDerateAmount(decrateAmount);
        orderInfoVo.setOriginalAmount(originAmount);
        orderInfoVo.setOrderDetailVoList(orderDetailVoList);
        orderInfoVo.setOrderDerateVoList(orderDerateVoList);
        orderInfoVo.setTradeNo(tradeNo);
        orderInfoVo.setTimestamp(System.currentTimeMillis());
        orderInfoVo.setItemType(itemType);
        //5.3 本次结算签名--防止数据篡改
        //5.3.1 将订单VO转为Map-将VO中支付方式null值去掉
        Map<String, Object> paramsMap = BeanUtil.beanToMap(orderInfoVo, false, true);
        System.out.println(paramsMap);
        //5.3.2 调用签名API对现有订单所有数据进行签名
        String sign = SignHelper.getSign(paramsMap);
        orderInfoVo.setSign(sign);

        //6.返回订单确认页数据VO对象
        return orderInfoVo;

//        //1.创建订单确认页数据VO对象
//        OrderInfoVo orderInfoVo = new OrderInfoVo();
//        //1.1 订单信息VO封装-购买项目类型
//        orderInfoVo.setItemType(tradeVo.getItemType());
//        //1.1.声明订单中相关价格-初始值设置为"0.00"，在后续业务中赋值即可
//        BigDecimal originalAmount = new BigDecimal("0.00");
//        BigDecimal derateAmount = new BigDecimal("0.00");
//        BigDecimal orderAmount = new BigDecimal("0.00");
//
//        //1.2 声明初始化订单明细列表及订单优惠明细列表，在后续业务中向集合中新增对象
//        List<OrderDetailVo> orderDetailVoList = new ArrayList<>();
//        List<OrderDerateVo> orderDerateVoList = new ArrayList<>();
//
//        //2.处理订单确认页数据-选择VIP会员
//        if (SystemConstant.ORDER_ITEM_TYPE_VIP.equals(tradeVo.getItemType())) {
//            //2.1 远程调用“用户服务”获取套餐详情
//            VipServiceConfig vipServiceConfig = userFeignClient.getVipServiceConfig(tradeVo.getItemId()).getData();
//            Assert.notNull(vipServiceConfig, "VIP套餐：{}不存在", tradeVo.getItemId());
//            //2.2 封装订单中VIP会员价格 原价=减免价+订单价
//            originalAmount = vipServiceConfig.getPrice();
//            orderAmount = vipServiceConfig.getDiscountPrice();
//            derateAmount = originalAmount.subtract(orderAmount);
//            //2.3 封装订单中商品明细列表
//            OrderDetailVo orderDetailVo = new OrderDetailVo();
//            orderDetailVo.setItemPrice(originalAmount);
//            orderDetailVo.setItemId(tradeVo.getItemId());
//            orderDetailVo.setItemName(vipServiceConfig.getName());
//            orderDetailVo.setItemUrl(vipServiceConfig.getImageUrl());
//            orderDetailVoList.add(orderDetailVo);
//
//            //2.4 封装订单中优惠明细列表
//            OrderDerateVo orderDerateVo = new OrderDerateVo();
//            orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_VIP_SERVICE_DISCOUNT);
//            orderDerateVo.setDerateAmount(derateAmount);
//            orderDerateVo.setRemarks("VIP限时优惠：" + derateAmount);
//            orderDerateVoList.add(orderDerateVo);
//
//        } else if (SystemConstant.ORDER_ITEM_TYPE_ALBUM.equals(tradeVo.getItemType())) {
//            //3. TODO 处理订单确认页数据-选择专辑
//
//        } else if (SystemConstant.ORDER_ITEM_TYPE_TRACK.equals(tradeVo.getItemType())) {
//            //4. TODO 处理订单确认页数据-选择声音
//
//        }
//
//        //5.所有订单确认都需要属性
//        orderInfoVo.setOriginalAmount(originalAmount);
//        orderInfoVo.setOrderAmount(orderAmount);
//        orderInfoVo.setDerateAmount(derateAmount);
//        orderInfoVo.setOrderDetailVoList(orderDetailVoList);
//        orderInfoVo.setOrderDerateVoList(orderDerateVoList);
//        //5.1 本次结算流水号-防止重复提交
//        //5.1.1 构建当前用户本次订单流水号Key
//        String tradeNoKey = RedisConstant.ORDER_TRADE_NO_PREFIX + userId;
//        //5.1.2 生成本次订单流水号
//        String tradeNo = IdUtil.fastSimpleUUID();
//        //5.1.3 将流水号存入Redis
//        redisTemplate.opsForValue().set(tradeNoKey, tradeNo, 5, TimeUnit.MINUTES);
//        //5.1.4 封装订单VO中流水号
//        orderInfoVo.setTradeNo(tradeNo);
//
//        //5.2 本次结算时间戳
//        orderInfoVo.setTimestamp(DateUtil.current());
//        //5.3 本次结算签名--防止数据篡改
//        //5.3.1 将订单VO转为Map-将VO中支付方式null值去掉
//        Map<String, Object> paramsMap = BeanUtil.beanToMap(orderInfoVo, false, true);
//        //5.3.2 调用签名API对现有订单所有数据进行签名
//        String sign = SignHelper.getSign(paramsMap);
//        orderInfoVo.setSign(sign);
//
//        //6.返回订单确认页数据VO对象
//        return orderInfoVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> submitOrder(OrderInfoVo orderInfoVo) {
        //根据传入的信息 进行订单的提交
        //需要向前端传递一个OrderNo
        //基于数据 需要进行重复提交的判断 可以通过在订单结算前的分布式锁来进行校验
        //获取分布式锁然后删除 删除后就可以防止重复提交订单信息 无法删除分布式锁的订单请求就是重复提交
        //5.1.1 构建当前用户本次订单流水号Key
        Long userId = AuthContextHolder.getUserId();
        UserInfoVo userInfoVo = userFeignClient.getUserVoById(userId).getData();
        Assert.notNull(userInfoVo, "该用户数据不存在");
        String tradeNoKey = RedisConstant.ORDER_TRADE_NO_PREFIX + userId;
        //5.1.2 生成本次订单流水号
        String scriptText = "if(redis.call('get', KEYS[1]) == ARGV[1]) then return redis.call('del', KEYS[1]) else return 0 end";

        //2.2 执行脚本，如果脚本返回结果为false 抛出异常即可
        DefaultRedisScript<Boolean> redisScript = new DefaultRedisScript<>(scriptText, Boolean.class);
        boolean flag = (boolean) redisTemplate.execute(redisScript, Arrays.asList(tradeNoKey), orderInfoVo.getTradeNo());
        //校验是否重复提交订单
        if (!flag) {
            throw new GuiguException(500, "订单重复提交");
        }
        //订单校验 防止订单信息被篡改
        Map<String, Object> map = BeanUtil.beanToMap(orderInfoVo, false, true);
        map.remove("payWay");
        System.out.println(map);
        SignHelper.checkSign(map);
        //校验成功后需要对订单信息进行保存
        //但是创建订单有三类 vip 专辑 声音
        //初始化订单编号
        String orederNo = IdUtil.fastSimpleUUID().toLowerCase().toString();
        OrderInfo orderInfo = new OrderInfo();
        BeanUtil.copyProperties(orderInfoVo, orderInfo);
        orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_UNPAID);

        orderInfo.setOrderNo(orederNo);
        orderInfo.setUserId(userId);
        //修改订单状态
        orderInfo.setUpdateTime(new Date());

        orderInfoMapper.insert(orderInfo);
        Long orderId = orderInfo.getId();
        for (OrderDetailVo orderDetailVo : orderInfoVo.getOrderDetailVoList()) {
            OrderDetail orderDetail = BeanUtil.copyProperties(orderDetailVo, OrderDetail.class);
            orderDetail.setOrderId(orderId);
            detailMapper.insert(orderDetail);
        }
        for (OrderDerateVo orderDerateVo : orderInfoVo.getOrderDerateVoList()) {
            OrderDerate orderDerate = BeanUtil.copyProperties(orderDerateVo, OrderDerate.class);
            orderDerate.setOrderId(orderId);
            derateMapper.insert(orderDerate);
        }
        if (SystemConstant.ORDER_PAY_ACCOUNT.equals(orderInfoVo.getPayWay())) {
            //            账户表user_account user_account_detail 修改账户信息及生成账户变化信息
            AccountLockVo accountLockVo = new AccountLockVo();
            accountLockVo.setOrderNo(orederNo);
            accountLockVo.setAmount(orderInfoVo.getOrderAmount());
            accountLockVo.setUserId(userId);
            UserPaidRecordVo userPaidRecordVo = new UserPaidRecordVo();
            userPaidRecordVo.setOrderNo(orederNo);
            userPaidRecordVo.setUserId(userId);
            userPaidRecordVo.setItemType(orderInfoVo.getItemType());
            List<Long> itemIds = orderInfoVo.getOrderDetailVoList().stream().map(OrderDetailVo::getItemId).collect(Collectors.toList());
            userPaidRecordVo.setItemIdList(itemIds);
            userFeignClient.savePaidRecord(userPaidRecordVo);
            //提交vip生成订单
            if (orderInfoVo.getItemType().equals(SystemConstant.ORDER_ITEM_TYPE_VIP)) {
                accountLockVo.setContent("购买vip服务");
//            AccountLockResultVo lockResultVo = accountFeignClient.checkAndLock(accountLockVo).getData();
//            Assert.notNull(lockResultVo,"锁定用户余额失败");
            } else if (SystemConstant.ORDER_ITEM_TYPE_ALBUM.equals(orderInfoVo.getItemType())) {
                //专辑定订单的提交 提交专辑订单需要涉及
                //album_info 查询数据
                //user_account user_account_detail user_paid_album(后续支付成功回调)
                accountLockVo.setContent("购买整本专辑");
                //TODO 专辑购买后需要添加专辑购买统计量
            } else if (SystemConstant.ORDER_ITEM_TYPE_TRACK.equals(orderInfoVo.getItemType())) {
                //声音的订单提交涉及user_paid_track
                //user_account user_account_detail user_paid_track(后续支付成功回调)
                accountLockVo.setContent("购买声音");

            }
            orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_PAID);
            orderInfoMapper.updateById(orderInfo);
            accountFeignClient.updateAccount(accountLockVo);
        }
        if (SystemConstant.ORDER_PAY_WAY_WEIXIN.equals(orderInfoVo.getPayWay())) {

        }
        //封装订单号
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("orderNo", orderInfo.getOrderNo());
        delayMessage.sendDelayMsg(MqConst.QUEUE_ORDER_CANCEL, orederNo, Long.valueOf(10));
//        String orderKey = RedisConstant.ORDER_TRADE_NO_PREFIX+userId+":"+orederNo;
//            redisTemplate.opsForValue().set(orderKey,orderInfo,RedisConstant.CACHE_TEMPORARY_TIMEOUT,TimeUnit.SECONDS);
        return resultMap;
    }

    @Override
    public void updateCancelOrder(String orderNo) {
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo));

        orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_CANCEL);
        orderInfo.setUpdateTime(new Date());
        orderInfoMapper.updateById(orderInfo);
    }

    @Override
    public Page<OrderInfo> findUserPage(Page<OrderInfo> page) {
        Long userId = AuthContextHolder.getUserId();
        page = orderInfoMapper.findUserPage(page, userId);
        List<OrderInfo> collect = page.getRecords().stream().map(orderInfo -> {
                    orderInfo.setPayWayName(getPayName(orderInfo.getPayWay()));
                    return orderInfo;
                }
        ).collect(Collectors.toList());
        page.setRecords(collect);
        return page;
    }

    @Override
    public OrderInfo getOrderInfo(String orderNo) {
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo));
        List<OrderDetail> orderDetails = detailMapper.selectList(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderId, orderInfo.getId()));
        orderInfo.setOrderDetailList(orderDetails);
        orderInfo.setPayWayName(getPayName(orderInfo.getPayWay()));
        return orderInfo;
    }

    @Override
    public void orderPaySuccess(String orderNo) {
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo));
        orderInfoMapper.update(orderInfo,new LambdaUpdateWrapper<OrderInfo>().eq(OrderInfo::getOrderNo,orderNo).set(OrderInfo::getOrderStatus,SystemConstant.ORDER_STATUS_PAID));
    }

    private String getPayName(String payWay) {
        switch (payWay) {
            case SystemConstant.ORDER_PAY_WAY_WEIXIN -> {
                return "微信";
            }
            case SystemConstant.ORDER_PAY_WAY_ALIPAY -> {
                return "支付宝";
            }
            case SystemConstant.ORDER_PAY_ACCOUNT -> {
                return "余额";
            }
        }
        return "";
    }
}
